# -*- coding: utf-8 -*-
# @Time    : 2024/1/16  23:03
# @Author  : zhanghao
# @FileName: task_manager.py
# @Software: PyCharm
"""
    Description: 任务管理者
"""
from db.sqlite import Sqlite
from config.logger import Logger
from api.domain.file_result import FileResult
from api.request.task_request import TaskReq
from api.request.config_rule import ConfigRule
from api.response.task_response import TaskResponse
from multiprocessing import Pipe
from domain.signal_unit import SignalUnit
from helper.event_type import EventType

import os
import json


class TaskManager:
    logger = Logger.get()

    conn_main: Pipe

    sqlite: Sqlite

    def __init__(self):
        self.sqlite = Sqlite()
        self.sqlite.initTaskTable()

    def addPipe(self, conn_main: Pipe):
        self.conn_main = conn_main

    def taskSubmit(self, task_req: TaskReq):
        if task_req.link_type != 'oss':
            return TaskResponse.buildFailed('不支持' + task_req.link_type + '文件方式')

        batch_data = []
        for file in task_req.file_info:
            single_data = (file.file_id, 'oss', file.file_link, 0, 0, '', '', '', '{}')
            batch_data.append(single_data)

        self.sqlite.batchInsertTask(batch_data)
        return TaskResponse.buildSuccess()

    def configRule(self, config_rule: ConfigRule) -> TaskResponse:
        self.logger.info(config_rule)

        if config_rule and config_rule.classifyId:
            current_dir = os.getcwd()
            rule_path = current_dir + '/conf/config.json'
            with open(rule_path, 'r', encoding='utf-8') as f:
                rule_json = json.load(f)
            self.logger.info('配置内容为：' + str(rule_json))

            # 比较配置内容后更新
            is_new = True
            for rule in rule_json['rules']:
                if rule['classifyId'] == config_rule.classifyId:
                    is_new = False
                    # 更新
                    rule['type'] = config_rule.type
                    rule['keyword'] = config_rule.keyword
                    rule['retFileName'] = config_rule.retFileName

                    rule['grabContent']['words'] = []
                    for word in config_rule.grabContent.words:
                        rule['grabContent']['words'].append(word)

                    rule['grabContent']['fields'] = []
                    for field in config_rule.grabContent.fields:
                        rule['grabContent']['fields'].append(field)

            if is_new:
                rule_json['rules'].append(config_rule.model_dump())

            with open(rule_path, 'w', encoding='utf-8') as file:
                json.dump(rule_json, file, indent=4, ensure_ascii=False)

            event = SignalUnit.build(EventType.UPDATE_CONFIG, FileResult.buildBlank())
            self.logger.info(event)
            self.conn_main.send(event)

        self.logger.info('配置更新成功')
        return TaskResponse.buildSuccess()

    def taskQuery(self, file_id) -> FileResult:
        file_result = FileResult.buildBlank()
        if file_id is None:
            return file_result

        response = TaskResponse.buildSuccess()
        result = self.sqlite.taskQuery(file_id)
        if result is None:
            return response

        file_result = FileResult.build(result[0], result[1], result[2], result[3], result[4],
                                       result[5], result[6], result[7], result[8], result[9])
        response = TaskResponse.buildSuccess()
        response.setData(file_result)

        return response
